package HDAPI.examples;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import HDAPI.HDBase;

public class DownloadExample extends HttpServlet 
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
    	Utility.initHDAPISettings(this.getServletContext());
        
        PrintWriter out = response.getWriter();

        HDBase hd = new HDBase();
		if(hd.download()){
			out.println(hd.getDownloadFile().getAbsolutePath());
			response.setContentType("application/json");
			writeDownloadedFile(hd, response);
		}else{
			response.setContentType("text/html");
			out.println("Request failed.<br>");
			Utility.dumpError(hd, out);
		}

		
    }
    
    private void writeDownloadedFile(HDBase hd, HttpServletResponse response)
    throws IOException
    {
    	OutputStream out = response.getOutputStream();
    	FileInputStream is = new FileInputStream(hd.getDownloadFile());
    	byte b = -1;
    	while ( (b = (byte)is.read()) != -1) {
    		out.write(b);
    	}
    	out.flush();
    	out.close();
    	is.close();
    }
}